<?php
namespace Apps\Csoap\Controllers;

use Phalcon\Mvc\Controller;
use Apps\Csoap\Controllers\BaseController;
use PhalconPlus\Common\ResponseResultStatus;
use Apps\Common\Models\Branch;
use Apps\Common\Models\BeautyParlor;
use Apps\Common\Models\BeautyParlorPhotos;
use Apps\Common\Models\BeautyParlorTag;
use Apps\Common\Models\SysAreaZipDistrictPhonecode;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\BeautyParlorTagInfo;
use PhalconPlus\Common\ResponseResult;
use Phalcon\Mvc\Model;
use Apps\Common\Models\BeautyParlorAttr;
use Apps\Common\Models\BeautyParlorService;


class OnlineparlorController extends BaseController 
{
    public function initialize(){
        parent::initialize();
    }
    
    /**
     * 查询店铺信息
     * @date: 2016年2月27日 
     * @author: 545
     */
    public function beautyinfoAction(){
        
        $this->view->disable();
        
        $shop_id = $this->getDataItem('shop_id');//分店id
        
        if (empty($shop_id)){
            $this->senderror(ResponseResultStatus::POST_BODY_PARAM_ERROR,'业务数据不全');
        }

        //验证分店是否通过审核
        $branch = Branch::findFirst("shop_id = $shop_id AND status = 200");

        if (!$branch){
            $this->senderror(ResponseResultStatus::BUSINESS,'分店未通过开通线上店铺申请');
        }
        else {
            // 获取美容院信息
            $info = BeautyParlor::query()
                ->columns([
                    'bp_id',
                    'bp_name',
                    'bp_cover',
                    'bp_address',
                    'bp_district',
                    'bp_tel',
                    'bp_intro',
                    'bp_state',
                    'bp_is_sell',
                    'bp_medal',
                    'bp_owner_mobile',
                    'bp_addtime',
                    'X(bp_coordinate) latitude',
                    'Y(bp_coordinate) longitude',
                    'bpa.open_time',//每日开始营业时间
                    'bpa.close_time',//每日停止营业时间
                    'bpa.low_price',//起步价
                    'bpa.open_year',//开业年限
                    'bpa.shop_area',//店铺面积
                    'bpa.service_num',//服务项目多少项
                    'bpa.facilities'//设备设施
                ])
                ->leftJoin('Apps\Common\Models\BeautyParlorAttr','Apps\Common\Models\BeautyParlor.bp_id = bpa.beauty_parlor_id','bpa')
                ->where('Apps\Common\Models\BeautyParlor.bp_state>0 and Apps\Common\Models\BeautyParlor.branch_id=:bid:')
                ->bind(['bid' => $shop_id])
                ->execute()->getFirst();

                if($info){
                    $info = $info->toArray();
                }
                
            if (!$info) {
                $this->sendResult(ResultStatus::QUERY_DATA_NOT_EXIST,"","未找到数据");
            }
            else {

                $info['facilities'] = json_decode($info['facilities'])?json_decode($info['facilities']):null;
                //美容院图片
                $pics = BeautyParlorPhotos::query()
                ->columns(['photo_url', 'photo_id'])
                ->where('photo_state>0 and beauty_parlor_id=:bid:')
                ->bind(['bid' => $info['bp_id']])
                ->execute()->toArray();
                
                $info['pics'] = $pics;
                //美容院标签
                $tagList = $this->getBeautyParlorTags($info['bp_id']);
                $tagListDataIds = [];
                $tagListDataTitles = [];
                foreach ($tagList as $tag) {
                    $tagListDataIds[] = $tag->tag_id;
                    $tagListDataTitles[] = $tag->tag_title;
                }
                $tagListData = [
                    implode(',', $tagListDataIds),
                    implode(',', $tagListDataTitles),
                ];

                $info['tags'] = $tagListData;
                $area = $this->getDistrictInfo($info['bp_district']);
                $info['bpArea'] = $area;
                $this->sendResult(ResponseResultStatus::SUCCESS,$info,'');
            }
        }
    }
    
    
    /**
     * 
     * @date: 2016年3月16日 
     * @author: 545
     */
    public function modifybeautyAction(){
        $this->view->disable();
        $bp_id = $this->getDataItem('bp_id');
        $name = $this->getDataItem('bp_name');
        $bpCover = $this->getDataItem('bp_cover');
        $tel = $this->getDataItem('bp_tel');
        $medalRefund = intval($this->getDataItem('bp_medal_refund',0));
        $medalVerify = intval($this->getDataItem('bp_medal_verify',0));
        $tags = $this->getDataItem('bp_tags');
        $ownerMobile = $this->getDataItem('bp_owner_mobile');
        $intro = $this->getDataItem('bp_intro');
        $branch_id = $this->getDataItem('shop_id');
       
        ////////////////////////////////////2.0新加参数////2.0新加参数///////2.0新加参数///////2.0新加参数///////////////////////////////
        $low_price=$this->getDataItem("low_price",0);//起步价                                                                 
        $open_year=$this->getDataItem("open_year",0);//开业年限                                                                   
        $shop_area=$this->getDataItem("shop_area",0);//店铺面积                                                            
        $service_num=$this->getDataItem("service_num",0);//服务项目数量                                                   
        $op_cl_time=$this->getDataItem("time",'');//营业时间     
		$facilities=$this->getDataItem("facilities",'');//设备设施 
        if($op_cl_time!=''){                                                                                                                        
        	$op_cl_time_arr=explode("至",$op_cl_time);                                                                    
        	$open_time=trim($op_cl_time_arr[0]);                                                                      
        	$close_time=trim($op_cl_time_arr[1]);                                                                    
        }else{                                                                                                     
        	$open_time='';
        	$close_time='';
        }
        if($facilities!=''){
	        try {
	        	$facilities_json=json_encode($facilities);
	        }catch (\Exception $e){
	            $facilities_json = null;
	        }
        }else{
        	$facilities_json=null;
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        
        try {
        	$this->db->begin();
        	
        	if($branch_id!=''){
        		$info=Branch::findFirst("shop_id = $branch_id");
        		if ($info){
        		    $info = $info->toArray();
        		}
        	}
        	// 保存基础数据
        	$bp = BeautyParlor::findFirst("bp_id = {$bp_id} AND branch_id = {$branch_id}");
        	
        	$temp['bp_name'] = $name;
        	$temp['bp_cover'] = $bpCover;
        	$temp['bp_tel'] = $tel;
        	$temp['bp_owner_mobile'] = $ownerMobile;
        	$temp['bp_intro'] = $intro;
        	$temp['bp_medal'] = strval($medalRefund) . strval($medalVerify);

        	if($branch_id != ''){
        		$temp['long_time']=$info->long_time;
        		$temp['start_time']=$info->start_time;
        		$temp['end_time']=$info->end_time;
        	}

        	$rs_bp = $bp -> update($temp);
        	if($rs_bp == false){
        		return $this->senderror(ResultStatus::DATABASE_ERROR,"写入基础数据失败");
        	}
        	/*保存美容院相关数据  */
        	$bp_attr=BeautyParlorAttr::findFirst("beauty_parlor_id = {$bp_id}");
        	$bp_attr->close_time=$close_time;
        	$bp_attr->open_time=$open_time;
        	$bp_attr->low_price=$low_price;
        	$bp_attr->open_year=$open_year;
        	$bp_attr->facilities=$facilities_json;
        	$bp_attr->service_num=$service_num;
        	$bp_attr->shop_area=$shop_area;
        	if(!$bp_attr->save()){
        		return $this->senderror(ResultStatus::DATABASE_ERROR,"写入扩展数据失败");
        	}
        	//处理标签
            foreach($tags as $tag) {
                $tagDb = BeautyParlorTag::query()
                    ->columns('bp_tag_id, bp_id, tag_id')
                    ->where('bp_id = :bid: AND tag_id = :tid:')
                    ->bind(['bid'=>$bp_id, 'tid'=>$tag])
                    ->execute()->getFirst();
                if(!$tagDb) {
                    $tagDb = new BeautyParlorTag();
                    $tagDb->bp_id = $bp_id;
                    $tagDb->tag_id = $tag;
                    if ($tagDb->save() == false) {
                        $this->databaseErrorLog($tagDb);
                    }
                }
            }
            
            // 获取所有的标签删除已取消的标签
            $tagList = BeautyParlorTag::query()
                ->where('bp_id = :bid:')
                ->bind(['bid'=>$bp_id])
                ->execute();
            foreach($tagList as $t) {
                if(in_array(strval($t->tag_id), $tags) == false) {
                    $t->delete();
                }
            }
        	// 保存轮播图片
        	// 轮播图片
    	    $pic = $this->getDataItem('pics');
    	    $pics = explode(',', $pic);
    	    if (!empty($pics)){
    	        foreach($pics as $pic) {
    	            $picDb = new BeautyParlorPhotos();
    	            $picDb->beauty_parlor_id = $bp_id;
    	            $picDb->photo_url = $pic;
    	            $rs_pic = $picDb -> save();
    	            if($rs_pic == false){
    	            				$this->senderror(ResultStatus::DATABASE_ERROR,'写入图片失败');
    	            }
    	        }
    	    }
        	$this->db->commit();
        	return $this->sendResult(ResultStatus::SUCCESS,['id'=>$bp_id,'success'=>1],'修改成功');
        } catch (\Exception $e) {
        	$this->db->rollback();
        }
        
        return $this->sendResult(ResultStatus::DATABASE_ERROR,'写入数据失败');
    }
    
    /**
     * 删除图片
     * @date: 2016年3月1日 
     * @author: 545
     */
    public function delphotoAction(){
        $bpId = intval($this->getDataItem('bid', 0));
        $picId = intval($this->getDataItem('pid', null, 0));
        $picDb = BeautyParlorPhotos::findFirst('photo_id = ' . $picId . ' AND beauty_parlor_id = ' . $bpId);
        if($picDb) {
            $rs = $picDb->update(['photo_state'=>-1]);
            if ($rs){
                $this->sendResult(ResultStatus::SUCCESS,['success'=>1],'ok');
            }
            else {
                $this->senderror(ResultStatus::DATABASE_ERROR,'数据库异常');
            }
        }
        else {
            $this->senderror(ResultStatus::QUERY_DATA_NOT_EXIST,"查询的数据不存在");
        }
    }
    
    /**
     * 标签列表
     * @date: 2016年3月1日 
     * @author: 545
     */
    public function tagsAction(){
        $tags = BeautyParlorTagInfo::query()
            ->columns('tag_id id, tag_title title')
            ->where('tag_state = 1 and parent_id != 0')
            ->execute()->toArray();
        
        $this->sendResult(ResponseResultStatus::SUCCESS,$tags);
    }
    
    private function getBeautyParlorTags($id)
    {
        return BeautyParlorTag::query()
            ->columns([
                'bp_tag_id',
                'tag_title',
                'Apps\Common\Models\BeautyParlorTag.tag_id tag_id'
            ])
            ->leftJoin('Apps\Common\Models\BeautyParlorTagInfo', 'ti.tag_id = Apps\Common\Models\BeautyParlorTag.tag_id', 'ti')
            ->where('bp_id = :id: AND tag_state > 0', ['id'=>$id])
            ->orderby("Apps\Common\Models\BeautyParlorTag.sort asc")
            ->execute();
    }
    
    private function getDistrictInfo($id)
    {
        return SysAreaZipDistrictPhonecode::findFirst('K_ID = ' . $id);
    }
}